package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.commen.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

//菜品管理
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;

    //新增菜品
@PostMapping
    public R<String> save(@RequestBody DishDto dishDto){//因为dishflaver list中提交的是json数据，所以要加RequestBody注解
    log.info(dishDto.toString());
  dishService.saveWithFlavor(dishDto);
  return R.success("新增菜品成功");
}

//分页查询
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
/*
        //定义Dish分页对象
        Page<Dish> dishPage = new Page<>(page,pageSize);

        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        //添加排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);

        //执行分页查询
        dishService.page(dishPage,queryWrapper);

        //定义一个集合，用于存储所有Dish的对象们
        List<Dish> dishes = dishPage.getRecords();//获取到所有dish对象

        //定义DishDto分页对象
        Page<DishDto> dishDtoPage = new Page<>(page,pageSize);
        //定义一个集合，用于存储所有DishDto的对象们
        List<DishDto> DishDtos = new ArrayList<>();
        //List<DishDto> dishDtos = dishDtoPage.getRecords();和上面一行意思一样，上面的老师说更好理解

        //转换：将每个dishes中的dish，转成DishDtos中的DishDto对象
        for (Dish dish : dishes) {
            DishDto dishDto = new DishDto();
            //赋值每个dish的所有字段到DishDto中
            BeanUtils.copyProperties(dish,dishDto);
            //从dish对象中获取分类id：categoryId
            Long categoryId = dish.getCategoryId();
            //通过分类id获取到分类对象
            Category categoryServiceForName = categoryService.getById(categoryId);
            //从分类对象中获取到分类名称，赋值给dishDto中的categoryName属性
            dishDto.setCategoryName(categoryServiceForName.getName());
            //将赋值了成员变量的dishDto对象放入DishDtos的集合中
            DishDtos.add(dishDto);



        }
        //将dishDto的集合，放入page<DishDto>中，作为分页数据
        dishDtoPage.setRecords(DishDtos);
        //将之前查询到的total数据，放到dto的page中
        dishDtoPage.setTotal(dishPage.getTotal());

        return R.success(dishDtoPage);*/


        //定义Dish分页对象
        Page<Dish> dishPage = new Page<>(page,pageSize);
        //条件构造器
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
      dishLambdaQueryWrapper.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        //添加排序条件
dishLambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);
        //执行分页查询
     dishService.page(dishPage,dishLambdaQueryWrapper);

        //定义一个集合，用于存储所有Dish的对象们
        List<Dish> dishes = dishPage.getRecords();

        //定义DishDto分页对象
        Page<DishDto> dishDtoPage = new Page<>(page,pageSize);

        //定义一个集合，用于存储所有DishDto的对象们
        List<DishDto> DishDtos = new ArrayList<>();
        //List<DishDto> dishDtos = dishDtoPage.getRecords();和上面一行意思一样，上面的老师说更好理解


        //转换：将每个dishes中的dish，转成DishDtos中的DishDto对象
        for (Dish dish : dishes) {
            DishDto dishDto = new DishDto();
            //赋值每个dish的所有字段到DishDto中
BeanUtils.copyProperties(dish,dishDto);
            //从dish对象中获取分类id：categoryId
            Long categoryId = dish.getCategoryId();
            //通过分类id获取到分类对象
            Category categoryServiceById = categoryService.getById(categoryId);
            //从分类对象中获取到分类名称，赋值给dishDto中的categoryName属性
            dishDto.setCategoryName(categoryServiceById.getName());
            //将赋值了成员变量的dishDto对象放入DishDtos的集合中
           DishDtos.add(dishDto);


        }
        //将dishDto的集合，放入page<DishDto>中，作为分页数据
        dishDtoPage.setRecords(DishDtos);
        //将之前查询到的total数据，放到dto的page中
        dishDtoPage.setTotal(dishPage.getTotal());
        return R.success(dishDtoPage);             //之前不理解的逻辑可言通过看CategoryController中的分类查询悟，就会了
    }

    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {//因为dishflaver list中提交的是json数据，所以要加RequestBody注解
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);
        return R.success("修改菜品成功");
    }
    /**
     * 根据id查询菜品信息和对应的口味信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    //根据条件查询对应的菜品数据
/*    @GetMapping("/list")
    public R<List<Dish>> list(Dish dish){
        //构造查询条件
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        dishLambdaQueryWrapper.eq(Dish::getStatus,1);
        //构造排序条件
        dishLambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(dishLambdaQueryWrapper);
        return R.success(list);
    }*/
//把上面的修改后，可用于front端
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null ,Dish::getCategoryId,dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        queryWrapper.eq(Dish::getStatus,1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);

        List<DishDto> dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
            //SQL:select * from dish_flavor where dish_id = ?
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);

            return dishDto;
        }).collect(Collectors.toList());

        return R.success(dishDtoList);
    }

}
